package com.framework.boc.admin.controller;

import com.bocnet.common.security.PKCS7Tool;
import com.framework.boc.admin.constant.BOCUrlConstant;
import com.framework.boc.admin.pay.body.BocPayRequestBody;
import com.framework.boc.admin.pay.body.RefundReqestBody;
import com.framework.boc.admin.pay.service.BocPayService;
import com.framework.boc.admin.utils.HttpClientUtil;
import com.framework.boc.controller.BaseController;
import com.framework.boc.error.CommonException;
import com.framework.boc.response.CommonResponse;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/boc-pay")
public class BocPayController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    BocPayService bocPayService;

    @PostMapping("/b2c-wx")
    public CommonResponse b2cRecvOrderWXAPP(@RequestBody BocPayRequestBody bocPayRequestBody) throws CommonException {
        String res = bocPayService.b2cRecvOrderWXAPP(bocPayRequestBody);
        return CommonResponse.success(res);
    }



    @GetMapping("/query-order")
    public CommonResponse queryOrder(@RequestParam("merchantNo") String merchantNo,
                                     @RequestParam("orderNos") String orderNos) {
        //2、加签
        //1、拼接原文
        StringBuffer sb = new StringBuffer();
        sb.append(merchantNo).append(":")
                .append(orderNos);
        String plainData = sb.toString();
        logger.info("原文="+plainData);
        String signData ="";
        try {
            //2、加签
            String pfxPath = this.getClass().getClassLoader().getResource("95566SZ045001692.pfx").getPath();
            //加签的证件和密码
            PKCS7Tool signer = PKCS7Tool.getSigner(pfxPath, "11111", "11111");
            signData = signer.sign(plainData.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //3、转BOC发送请求的参数
        List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
        formParams.add(new BasicNameValuePair("merchantNo", merchantNo));
        formParams.add(new BasicNameValuePair("orderNos", orderNos));
        formParams.add(new BasicNameValuePair("signData", signData));

        for (BasicNameValuePair basicNameValuePair : formParams) {
            logger.info(basicNameValuePair.getName()+"="+basicNameValuePair.getValue());
        }
        //4、发送请求
        String responseStr = HttpClientUtil.doPost(BOCUrlConstant.QUERYORDER, formParams);
        //5、返回结果:商户可以根据接口文档  自行处理xml报文格式的数据 如:返回结果字段多于文档则依据文档进行开发
        return CommonResponse.success(responseStr);
    }


    @GetMapping("/query-order-trans")
    public CommonResponse queryOrderTrans(@RequestParam("merchantNo") String merchantNo,
                                          @RequestParam("orderNo") String orderNo) {
        //2、加签
        //1、拼接原文
        StringBuffer sb = new StringBuffer();
        sb.append(merchantNo).append(":")
                .append(orderNo);
        String plainData = sb.toString();
        logger.info("原文="+plainData);
        String signData ="";
        try {
            //2、加签
            String pfxPath = this.getClass().getClassLoader().getResource("95566SZ045001692.pfx").getPath();
            //加签的证件和密码
            PKCS7Tool signer = PKCS7Tool.getSigner(pfxPath, "11111", "11111");
            signData = signer.sign(plainData.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //3、转BOC发送请求的参数
        List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
        formParams.add(new BasicNameValuePair("merchantNo", merchantNo));
        formParams.add(new BasicNameValuePair("orderNo", orderNo));
        formParams.add(new BasicNameValuePair("signData", signData));

        for (BasicNameValuePair basicNameValuePair : formParams) {
            logger.info(basicNameValuePair.getName()+"="+basicNameValuePair.getValue());
        }
        //4、发送请求
        String responseStr = HttpClientUtil.doPost(BOCUrlConstant.QUERYORDERTRANS, formParams);
        //5、返回结果:商户可以根据接口文档  自行处理xml报文格式的数据 如:返回结果字段多于文档则依据文档进行开发
        return CommonResponse.success(responseStr);
    }



    @PostMapping("/refund-order")
    public CommonResponse refundOrder(@RequestBody RefundReqestBody refundReqestBody) {
        String merchantNo = refundReqestBody.getMerchantNo();//商户号
        String mRefundSeq = refundReqestBody.getmRefundSeq();//退款交易流水号
        String curCode = refundReqestBody.getCurCode();//退款币种
        String refundAmount = refundReqestBody.getRefundAmount();//退款金额
        String orderNo = refundReqestBody.getOrderNo();//商户订单号 ，格式要求为：商户号（merchantNo）后6位+商户按自己规则生成的订单号；
        //2、加签
        //拼接原文
        StringBuffer sb = new StringBuffer();
        sb.append(merchantNo).append("|")
                .append(mRefundSeq).append("|")
                .append(curCode).append("|")
                .append(refundAmount).append("|")
                .append(orderNo);
        String plainData = sb.toString();
        logger.info("原文="+plainData);
        String signData ="";
        try {
            //2、加签
            String pfxPath = this.getClass().getClassLoader().getResource("95566SZ045001692.pfx").getPath();
            //加签的证件和密码
            PKCS7Tool signer = PKCS7Tool.getSigner(pfxPath, "11111", "11111");
            signData = signer.sign(plainData.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //3、转BOC发送请求的参数
        List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
        formParams.add(new BasicNameValuePair("merchantNo", merchantNo));
        formParams.add(new BasicNameValuePair("mRefundSeq", mRefundSeq));
        formParams.add(new BasicNameValuePair("curCode", curCode));
        formParams.add(new BasicNameValuePair("refundAmount", refundAmount));
        formParams.add(new BasicNameValuePair("orderNo", orderNo));
        formParams.add(new BasicNameValuePair("signData", signData));

        for (BasicNameValuePair basicNameValuePair : formParams) {
            logger.info(basicNameValuePair.getName()+"="+basicNameValuePair.getValue());
        }
        //4、发送请求
        String responseStrs = HttpClientUtil.doPost(BOCUrlConstant.REFUNDORDER, formParams);
        //5、返回结果:商户可以根据接口文档  自行处理xml报文格式的数据  如:返回结果字段多于文档则依据文档进行开发
        return CommonResponse.success(responseStrs);
    }




    @GetMapping("/get-ticket")
    public CommonResponse getTicket() {
        LocalDateTime orderTimeLocal = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String submitTime = dateTimeFormatter.format(orderTimeLocal);
        String fileDate = "20200826";
        String fileType = "HC";
        String handleType = "1";
        String merchantNo = "101132156648979";

        //2、加签
        //1、拼接原文
        StringBuffer sb = new StringBuffer();
        sb.append("fileDate=" + fileDate).append("|")
                .append("fileType=" + fileType).append("|")
            .append("handleType=" + handleType).append("|")
                .append("merchantNo=" + merchantNo).append("|")
                .append("submitTime=" + submitTime);
        String plainData = sb.toString();
        logger.info("原文="+plainData);
        String signData ="";
        try {
            //2、加签
            String pfxPath = this.getClass().getClassLoader().getResource("95566SZ045001692.pfx").getPath();
            //加签的证件和密码
            PKCS7Tool signer = PKCS7Tool.getSigner(pfxPath, "11111", "11111");
            signData = signer.sign(plainData.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //3、转BOC发送请求的参数
        List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
        formParams.add(new BasicNameValuePair("merchantNo", merchantNo));
        formParams.add(new BasicNameValuePair("handleType", handleType));
        formParams.add(new BasicNameValuePair("fileType", fileType));
        formParams.add(new BasicNameValuePair("fileDate", fileDate));
        formParams.add(new BasicNameValuePair("submitTime", submitTime));
        formParams.add(new BasicNameValuePair("signData", signData));

        for (BasicNameValuePair basicNameValuePair : formParams) {
            logger.info(basicNameValuePair.getName()+"="+basicNameValuePair.getValue());
        }
        //4、发送请求
        String responseStr = HttpClientUtil.doPost(BOCUrlConstant.B2CGETTICKET, formParams);
        //5、返回结果:商户可以根据接口文档  自行处理xml报文格式的数据 如:返回结果字段多于文档则依据文档进行开发
        return CommonResponse.success(responseStr);
    }



}
